package org.example;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;


@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Thread)
@Fork(1)
@Warmup(iterations = 3)
@Measurement(iterations = 10)
public class JMHMain {

    private static final VarHandle VAR_HANDLE;

    static {
        try {
            MethodHandles.Lookup mh = MethodHandles.privateLookupIn(ArrayList.class, MethodHandles.lookup());
            VAR_HANDLE = mh.findVarHandle(ArrayList.class, "elementData", Object[].class);
        } catch (Exception e) {
            System.out.println("加载 VarHandle 失败");
            throw new RuntimeException(e);
        }
    }

    @Benchmark
    public void testArrayListExtend() {
        arrayListExtend(1000000);
    }

    public void arrayListExtend(int arrNum) {
        ArrayList<Integer> arrList = new ArrayList<>();
        int extendCount = 0;
        Object[] elementData = (Object[]) VAR_HANDLE.get(arrList);
        int tmpCapacity = elementData.length;
        for (int i = 1; i <= arrNum + 1; i++) {
            arrList.add(i);
            elementData = (Object[]) VAR_HANDLE.get(arrList);
            if (tmpCapacity != elementData.length) {
                extendCount++;
                System.out.printf("成员个数：%d, 数组出现了扩容：%d ————>%d \n", arrList.size(), tmpCapacity, elementData.length);
                tmpCapacity = elementData.length;
            }
        }
        System.out.printf("累计添加了 %d 个数组元素，扩容次数: %d ,最后一个元素：%d\n", arrNum, extendCount, arrList.get(arrNum - 1));
    }

    public static void main(String[] args) throws Exception {
        Options opt = new OptionsBuilder()
                .include(JMHMain.class.getSimpleName())
                .build();
        new Runner(opt).run();
    }
}